package com.henu.rescue.controller;

import com.henu.rescue.entity.*;
import com.henu.rescue.entity.VO.AccidentVO;
import com.henu.rescue.entity.VO.HumanIdVO;
import com.henu.rescue.service.AccidentService;
import com.henu.rescue.service.CategoryService;
import com.henu.rescue.service.OrderService;
import com.henu.rescue.service.StaService;
import com.henu.rescue.utils.Page;
import com.henu.rescue.utils.Result;
import com.henu.rescue.utils.ResultEnums;
import com.henu.rescue.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("accident/")
@Api("事故信息管理controller")
@Slf4j
public class AccController {

    @Autowired
    private AccidentService accidentService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private StaService staService;

    @Autowired
    private CategoryService categoryService;


    @PostMapping("add")
    @ApiOperation("模拟接入事故数据(添加事故信息)")
    public Result add(@RequestBody Accident accident){
        accident.setAccDate(new Date());
        //事故的自然因素处理
        String natureIdString = accident.getNatureId();
        String[] arrStringNatureId = natureIdString.split(",");
        //得到自然因素int[] intNatureId
        int[] intNatureId = new int[arrStringNatureId.length];
        for (int i = 0; i < arrStringNatureId.length; i++) {
            intNatureId[i] = Integer.parseInt(arrStringNatureId[i]);
        }
        //将因素的id对应的tab_category表中的数据的num + 1
        for (int i = 0; i < intNatureId.length; i++) {
            categoryService.updateNumById(intNatureId[i]);
        }

        //事故人为因素处理
        Integer humanId = accident.getHumanId();
        //将humanId对应的数据num+1
        categoryService.updateNumById(humanId);
        accidentService.addAccident(accident);
        return new Result(ResultEnums.SUCCESS);
    }

    @ApiOperation("分页查询")
    @PostMapping("getAllByPage")
    public Result<Page<AccidentVO>> getAllByPage(@RequestBody Page<AccidentVO> page){
        String sortColumn = page.getSortColumn();
        if (StringUtils.isNotBlank(sortColumn)) {
            // 排序列不为空
            String[] sortColumns = {"acc_id"};
            List<String> sortList = Arrays.asList(sortColumns);
            if (!sortList.contains(sortColumn.toLowerCase())) {
                return new Result<>(ResultEnums.PARAMS_ERROR.getCode(), "排序参数不合法！");
            }
        }
        page.setSortMethod("ASC");
        page= accidentService.selectOAccInfoByPage(page);
        //得到没有数据库原生数据(自然因素和人为因素都还没有联表查询) 需要联表查询出数据后返回给前端
        List<AccidentVO> accidents = page.getList();
        for (int i = 0; i < accidents.size(); i++) {
            //处理自然因素
            AccidentVO accidentVO = accidents.get(i);
            String natureIdString = accidentVO.getNatureId();
            String[] strings = natureIdString.split(",");
            int[] natureIdInt = new int[strings.length];
            StringBuilder stringBuilder = new StringBuilder("");
            for (int j = 0; j < strings.length; j++) {
                natureIdInt[j] = Integer.parseInt(strings[j]);
                //根据自然因素id获取对应的自然因素名字
                String s = categoryService.selectNameById(natureIdInt[j]);
                if(j == 1){
                    //天气
                    stringBuilder.append("天气:").append(s);
                }
                if(j == 3){
                    //车型
                    stringBuilder.append(" 车型:").append(s);
                }
                if(j == 5){
                    //路面条件
                    stringBuilder.append(" 路面条件:").append(s);
                }
                if(j == 6){
                    //事故形态
                    stringBuilder.append(" 事故形态:").append(s);
                }

            }
            accidentVO.setNatureName(stringBuilder.toString());
            //处理人为因素
            Integer humanId = accidentVO.getHumanId();
            String s = categoryService.selectNameById(humanId);
            accidentVO.setHumanName(s);
        }
        return new Result(ResultEnums.QUERY_SUCCESS,page);
    }

    @ApiOperation("删除事故")
    @DeleteMapping("del/{accId}")
    public Result del(@PathVariable Integer accId){

        if(accId == null){
            return new Result(ResultEnums.DEL_ERROR,"删除失败！");
        }
        accidentService.delAccidentLogic(accId);
        return new Result(ResultEnums.SUCCESS,"事故信息删除成功！");
    }

    @ApiOperation("给事故分配救援服务点")
    @PostMapping ("distribute/{accId}")
    public Result distribute(@PathVariable Integer accId){
        Order order = new Order();
        UUID uuid = UUID.randomUUID();
        order.setOrderId(uuid.toString());
        order.setAccId(accId);
        //根据accId获取accident
        Accident accident = accidentService.selectById(accId);
        //System.out.println(accident);

        //表示还没有分配任务点
        if (accident.getOrderId() == null || StringUtils.isBlank(accident.getOrderId())){
            //得到该事故的位置信息
            String location = accident.getLocation();
            double[] accLocationInt = StringUtils.parseTwoDoubles(location);

            //查询所有的救援服务点的信息（没有被逻辑删除的），并且计算出距离最近的 && 没有处于忙碌状态的 救援服务点
            List<Station> stations = staService.selectAllLeisure();
            if(stations.size() < 1){
                return new Result(ResultEnums.IS_BUSY,"没有救援服务点");
            }
            Double minDistance = Double.MAX_VALUE;
            Integer minStaId = 0;
            for (int i = 0; i < stations.size(); i++) {
                //获取每个station的坐标并且转换成DOUBLE类型
                Station station = stations.get(i);
                String staLocation = station.getStaLocation();
                Integer staId = station.getStaId();
                double[] staLocationInt = StringUtils.parseTwoDoubles(staLocation);
                //计算距离
                double x1 = accLocationInt[0];
                double y1 = accLocationInt[1];
                double x2 = staLocationInt[0];
                double y2 = staLocationInt[1];

                double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));

                if(distance < minDistance){
                    minDistance = distance;
                    minStaId = staId;
                }
            }
            if(minStaId == 0){
                return new Result(ResultEnums.IS_BUSY,"没有救援服务点");
            }
            //先判定是否处于忙碌状态
            Integer status = staService.getStatusById(minStaId);
            if(status == 5){
                return new Result(ResultEnums.IS_BUSY);
            }
            //得到了距离最近的station的id
            order.setStationId(minStaId);
            //将order的状态设置为0----->已分配救援组织点
            order.setStatus(0);
            order.setCreateTime(new Date());
            orderService.initOrder(order);
            //给accident分配救援服务点
            accidentService.distribute(accId,order.getOrderId());


            //将主键为minStation的救援点的状态+1()
            //System.out.println(minStaId);
            staService.setBusyById(minStaId);
            return new Result(ResultEnums.SUCCESS);
        }
        return new Result(ResultEnums.ALREADY_DISTRIBUTE);
    }


    @ApiOperation("获取没有分配工单的事故")
    @PostMapping("noDistribute")
    public Result getAccidentByStatus(@RequestBody Page<Accident> page){
        page.setSortMethod("desc");
        String sortColumn = page.getSortColumn();
        if (StringUtils.isNotBlank(sortColumn)) {
            // 排序列不为空
            String[] sortColumns = {"acc_id"};
            List<String> sortList = Arrays.asList(sortColumns);
            if (!sortList.contains(sortColumn.toLowerCase())) {
                return new Result<>(ResultEnums.PARAMS_ERROR.getCode(), "排序参数不合法！");
            }
        }
        page= accidentService.selectNoDistributeByPage(page);
        return new Result(ResultEnums.QUERY_SUCCESS,page);
    }

    @ApiOperation("获取自然因素种类")
    @PostMapping("getNature/{levelId}")
    public Result getNature(@PathVariable Integer levelId){
        List<Category> categories = categoryService.selectIdNameByX(levelId);
        HashMap<Integer, String> idName = new HashMap<>();
        for (int i = 0; i < categories.size(); i++) {
            Category category = categories.get(i);
            idName.put(category.getId(),category.getCategoryName());
        }
        return new Result(ResultEnums.QUERY_SUCCESS,idName);
    }

    @ApiOperation("获取人为因素种类")
    @PostMapping("getHuman")
    public Result getHuman(){
        List<HumanIdVO> humanList = new ArrayList<>();
        List<TwoLevel> idNames = categoryService.selectIdNameY(2);
        HashMap<Integer, String> sub;
        for (int i = 0; i < idNames.size(); i++) {
            TwoLevel idName = idNames.get(i);
            HumanIdVO humanIdVO = new HumanIdVO();
            humanIdVO.setTwoLevelId(idName.getTwoLevelId());
            humanIdVO.setTwoLevelName(idName.getTwoLevelName());
            sub = new HashMap<>();
            List<Category> list = categoryService.selectIdNameByX(humanIdVO.getTwoLevelId());
           /*写到这里了*/
            for (int j = 0; j < list.size(); j++) {
                sub.put(list.get(j).getId(),list.get(j).getCategoryName());
            }
            humanIdVO.setSubCategory(sub);
            humanList.add(humanIdVO);
        }
        return new Result(ResultEnums.QUERY_SUCCESS,humanList);
    }
}
